package cn.sinokj.party.chineseFourParty.activity.base;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import java.util.Map;


import cn.sinokj.party.chineseFourParty.R;
import cn.sinokj.party.chineseFourParty.activity.LoginInActivity;
import cn.sinokj.party.chineseFourParty.app.App;
import cn.sinokj.party.chineseFourParty.service.HttpConstants;
import cn.sinokj.party.chineseFourParty.utils.AppManager;
import cn.sinokj.party.chineseFourParty.utils.PreferencesUtil;
import cn.sinokj.party.chineseFourParty.utils.logs.Logger;
import cn.sinokj.party.chineseFourParty.view.dialog.DialogShow;
import cn.sinokj.party.chineseFourParty.view.dialog.confirm.ConfirmDialog;
import cn.sinokj.party.chineseFourParty.view.dialog.confirm.ConfirmInterface;


/**
 * @author azzbcc Email: azzbcc@sina.com
 * @ClassName BaseActivity
 * @Description Activity 基类
 * @date 创建时间 2016年5月23日 下午4:26:57
 **/
@SuppressLint("Registered")
public class BaseActivity extends AppCompatActivity {
    protected Logger logger = Logger.getLogger();
    protected static final PreferencesUtil preferencesUtil = new PreferencesUtil(App
            .context);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppManager.addActivity(this);
    }


    /**
     * 调用web接口的一些变量设置
     *
     * @author azzbcc E-mail: azzbcc@sina.com
     * @version 创建时间：2015年10月28日 上午9:10:38
     */
    private Map<String, JSONObject> result;
    protected Handler httpHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            logger.i("", result);
            if (null == result) {
                logger.e(new NullPointerException("result"));
                DialogShow.closeDialog();
                return false;
            }
            try {
                JSONObject json = result.values().iterator().next();
                String status = json.optString("status");
                if ("sessionTimeOut".equals(status)) {
                    logout();
                    DialogShow.closeDialog();
                    return false;
                }
                JSONObject jsonObject = result.get(HttpConstants.RESULT);
                if (null == jsonObject) {
                    Toast.makeText(BaseActivity.this, "网络连接异常", Toast.LENGTH_SHORT).show();
                    DialogShow.closeDialog();
                    return false;
                }

                httpHandlerResultData(msg, jsonObject);
            } catch (Exception e) {
                logger.e(e);
            }
            return false;
        }
    });

    protected Map<String, JSONObject> getDataFunction(int what, int arg1, int arg2, Object obj) {
        return null;
    }

    protected void httpHandlerResultData(Message msg, JSONObject jsonObject) {
        DialogShow.closeDialog();
    }

    protected final class LoadDataThread implements Runnable {

        private Object obj;
        private int what, arg1, arg2;

        public LoadDataThread() {
        }

        public LoadDataThread(int what) {
            this.what = what;
        }

        public LoadDataThread(int what, Object obj) {
            this.what = what;
            this.obj = obj;
        }

        public LoadDataThread(int what, int arg1, int arg2, Object obj) {
            this.what = what;
            this.arg1 = arg1;
            this.arg2 = arg2;
            this.obj = obj;
        }

        @Override
        public void run() {
            result = getDataFunction(what, arg1, arg2, obj);
            Message msg = BaseActivity.this.httpHandler.obtainMessage(what, arg1, arg2, obj);
            msg.sendToTarget();
        }
    }

    /**
     * 退出当前账号 调用方式：this.logout();
     *
     * @author azzbcc E-mail: azzbcc@sina.com
     * @version 创建时间：2015年12月23日 上午10:41:04
     */
    protected final void logout() {
        Intent intent = new Intent(BaseActivity.this, LoginInActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }

    protected void setTextSize(TextView textView) {
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
    }
    /*public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
			setResult(RESULT_CANCELED);
			if (this instanceof MainActivity || this instanceof AboutAsActivity 
			 || this instanceof MineActivity || this instanceof AnnouncementActivity) {
				quitApplication();
				return false;
			}
			finish();
			return true;
		}
		return false;
	}*/

    /**
     * 退出程序操作 调用方法：this.quitApplication();
     *
     * @author azzbcc E-mail: azzbcc@sina.com
     * @version 创建时间：2015年12月21日 下午4:35:14
     */
    protected final void quitApplication() {
        ConfirmDialog.confirmAction(this, "确定退出么?", "退出", "取消", new ConfirmInterface() {
            @SuppressWarnings("deprecation")
            @Override
            public void onOkButton() {
                if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
                    Intent startMain = new Intent(Intent.ACTION_MAIN);
                    startMain.addCategory(Intent.CATEGORY_HOME);
                    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(startMain);
                    System.exit(0);
                } else {
                    ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
                    am.restartPackage(getPackageName());
                }
            }

            @Override
            public void onCancelButton() {
            }

            @Override
            public void onDismiss(DialogInterface dialog) {

            }
        });
    }

    /**
     * 新更新的dialog
     */
    private AlertDialog updateConfirmDialog;

    protected final void updateConfirmAction(String message, String okString, String cancelString,
                                             ConfirmInterface confirmIf) {
        String[] str = message.split(";");
        updateConfirmDialog = new AlertDialog.Builder(this, R.style.Dialog_round).create();
        updateConfirmDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    updateConfirmDialog.dismiss();
                }
                return false;
            }
        });
        final ConfirmInterface confirmInterface = confirmIf;
        updateConfirmDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (confirmInterface != null) {
                    confirmInterface.onDismiss(dialog);
                }
            }
        });
        updateConfirmDialog.setCancelable(true);
        updateConfirmDialog.show();
        updateConfirmDialog.setContentView(R.layout.new_update_dialog);
        TextView confirm = (TextView) updateConfirmDialog.findViewById(R.id.confirm_message);
        TextView cancel = (TextView) updateConfirmDialog.findViewById(R.id.cancel_bady);
        TextView ok = (TextView) updateConfirmDialog.findViewById(R.id.ok_bady);
        if (!TextUtils.isEmpty(message)) {
            String s = "";
            for (int i = 0, len = str.length; i < len; i++) {
                s = s + str[i] + "\n";
            }
            confirm.setText(s);
        }
        if (!TextUtils.isEmpty(okString)) {
            ok.setText(okString);
        } else {
            ok.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(cancelString)) {
            cancel.setText(cancelString);
        } else {
            cancel.setVisibility(View.GONE);
        }

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (confirmInterface != null) {
                    confirmInterface.onCancelButton();
                }
                updateConfirmDialog.dismiss();
            }
        });
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (confirmInterface != null) {
                    confirmInterface.onOkButton();
                }
                updateConfirmDialog.dismiss();
            }
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (null != this.getCurrentFocus()) {
            // 点击空白位置 隐藏软键盘
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
        return super.onTouchEvent(event);
    }
}
